package com.study.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 *分布式锁
 */
public class RecipesLock {

    private static String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
    private static RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    private static String path= "/zlx";
    private static String lockPath = "/curator_recipes_lock_path";
    private static CuratorFramework client = CuratorFrameworkFactory
            .builder()
            .connectString(connectStr)
            .sessionTimeoutMs(5000)
            .retryPolicy(retryPolicy)
            //指定命名空间
            // .namespace("")
            .build();

    public static void main(String[] args) {

        client.start();
        final InterProcessLock lock = new InterProcessMutex(client, lockPath);
        final CountDownLatch latch = new CountDownLatch(1);
        for(int i =0;i < 30;i++){
            new Thread(new Runnable() {
                public void run() {
                    try{
                        latch.await();
                        lock.acquire();
                    }catch (Exception e){

                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss|SSS");
                    System.out.println("生成订单号是：" + sdf.format(new Date()));
                    try{
                        lock.release();
                    }catch (Exception e){

                    }
                }
            }).start();
        }
        latch.countDown();
    }
}
